package org.example.controller;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.FontProvider;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;

import java.io.*;
import java.nio.charset.StandardCharsets;

public class HtmlToPdfExporter {

    /**
     * 将HTML字符串导出为PDF文件
     * @param htmlContent HTML内容字符串
     * @param outputPdfPath 输出的PDF文件路径
     * @throws IOException
     * @throws DocumentException
     */
    public static void exportToPdf(String htmlContent, String outputPdfPath) throws IOException, DocumentException {
        // 创建文档对象
        Document document = new Document();

        // 获取PDF写入器
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outputPdfPath));

        // 打开文档
        document.open();

        // 创建字体提供器，设置中文字体
        FontProvider fontProvider = new FontProvider() {
            @Override
            public boolean isRegistered(String fontName) {
                return true;
            }

            @Override
            public com.itextpdf.text.Font getFont(String fontname, String encoding, boolean embedded, float size, int style, com.itextpdf.text.BaseColor color) {
                try {
                    // 使用支持中文的字体
                    BaseFont bfChinese = BaseFont.createFont("simsun.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                    return new com.itextpdf.text.Font(bfChinese, size, style, color);
                } catch (Exception e) {
                    // 如果中文字体失败，回退到默认字体
                    try {
                        return new com.itextpdf.text.Font(BaseFont.createFont(), size, style, color);
                    } catch (DocumentException ex) {
                        throw new RuntimeException(ex);
                    } catch (IOException ex) {
                        throw new RuntimeException(ex);
                    }
                }
            }
        };

        // 设置XML Worker的字体提供器
        XMLWorkerHelper worker = XMLWorkerHelper.getInstance();

        // 将HTML内容转换为PDF
        worker.parseXHtml(writer, document,
                new ByteArrayInputStream(htmlContent.getBytes(StandardCharsets.UTF_8)),
                null, StandardCharsets.UTF_8, fontProvider);

        // 关闭文档
        document.close();
    }

    public static void main(String[] args) {
        // 示例HTML内容，包含中文和图片
        String htmlContent = "<!DOCTYPE html>\n" +
                "<html>\n" +
                "<head>\n" +
                "    <meta charset=\"UTF-8\" />\n" +
                "    <title>asd</title>\n" +
                "    <style>\n" +
                "        body { font-family: SimSun; }\n" +
                "    </style>\n" +
                "</head>\n" +
                "<body>\n" +
                "<h1 style=\"text-align: center\"><strong>测试PDF</strong></h1><p>阿斯顿法国红酒啊手动阀手动阀</p><p>去问人体与三个豆腐干地方</p>"+
                "</body>\n" +
                "</html>";

        try {
            // 导出PDF
            exportToPdf(htmlContent, "output.pdf");
            System.out.println("PDF导出成功！");
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("PDF导出失败: " + e.getMessage());
        }
    }
}